
package com.yimixian.app.user;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.ta.utdid2.android.utils.StringUtils;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.address.ShowAddressesActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.common.YmxTitleBarActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.MyFragment;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.KV;
import com.yimixian.app.model.LoginBanner;
import com.yimixian.app.model.User;
import com.yimixian.app.model.UserLevel;
import com.yimixian.app.net.HttpApi;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.util.DensityUtils;
import com.ymx.sdk.util.DeviceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class UserRegistrationActivity extends YmxTitleBarActivity {

    private static final String VERIFY_CODE_REGEX = "^\\d{6}$";
    private static final String PHONE_NUMBER_REGEX = "^1\\d{10}$";
    @InjectView(R.id.tv_agree)
    TextView mTvAgree;
    private int fromType = -2;

    @InjectView(R.id.phone_number_edit_text)
    EditText mPhoneNumberEditText;
    @InjectView(R.id.verify_code_edit_text)
    EditText mVerifyCodeEditText;
    @InjectView(R.id.get_verify_code_button)
    TextView mGetVerifyCodeButton;
    @InjectView(R.id.submit_verify_code_button)
    TextView mSubmitVerifyCodeButton;
    @InjectView(R.id.iv_login_banner)
    ImageView mIvLoginBanner;

    @InjectView(R.id.v_margin)
    View v_margin;

    @InjectView(R.id.btn_wx_login)
    View btn_wx_login;
    @InjectView(R.id.rl_hezuo)
    View  rl_hezuo;

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
    private SharedPreferences mSharedPreferences;
    private CountDownTimer mCountDownTimer;
    private PlusMinusIconMessage mPlusMinusIconMessage;
    LoginBanner loginBanner = null;
    private BroadcastReceiver receiver;
    private String uuid; //绑定手机号所需UUID
    private ProgressDialogFragment dialog;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_registration_activity);
        ButterKnife.inject(this);
        initBanner();
        EventBus.getDefault().registerSticky(this);
        mTvAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
                if (appConfig == null) {
                    return;
                }
                if (!TextUtils.isEmpty(appConfig.agreementUrl)) {
                    Intent intent = new Intent(UserRegistrationActivity.this, WebViewActivity.class);
                    intent.putExtra(WebViewActivity.EXTRA_TITLE, getString(R.string.login_agree_title));
                    intent.putExtra(WebViewActivity.EXTRA_URL, appConfig.agreementUrl);
                    startActivity(intent);
                }
            }
        });
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            fromType = bundle.getInt("fromType");
        }
        mYmxDataService = YmxDataService.getInstance();
        mDataManager = DataManager.getInstance();
        mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS_NAME,
                Context.MODE_PRIVATE);

        mVerifyCodeEditText.addTextChangedListener(new UserTextWatcher(
                new Runnable() {
                    @Override
                    public void run() {
                        onVerifyCodeChanged();
                    }
                }));
        mPhoneNumberEditText.addTextChangedListener(new UserTextWatcher(
                new Runnable() {
                    @Override
                    public void run() {
                        onPhoneNumberChanged();
                    }
                }));

        //微信联合登陆相关
        AppConfig mAppConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (mAppConfig == null)
            return;
        if("true".equals(mAppConfig.login_by_wechat)){
            rl_hezuo.setVisibility(View.VISIBLE);
            btn_wx_login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                            UMengConstants.NEW_WECHAT_LOGINBTN);

                    IWXAPI wxApi = WXAPIFactory.createWXAPI(UserRegistrationActivity.this, Constants.WECHAT_APP_ID);
                    if(!wxApi.isWXAppInstalled()){
                        UiUtils.showToast("您还没有安装微信客户端");
                    }else if(!wxApi.isWXAppSupportAPI()){
                        UiUtils.showToast("您的微信客户端版本过低");
                    }else{
//                        dialog = UiUtils.showProgressDialog(UserRegistrationActivity.this, "正在使用微信登陆,请稍后...");
                        dialogLoading = UiUtils.showLoadingDialog(UserRegistrationActivity.this, "正在使用微信登陆,请稍后...");
                        SendAuth.Req req = new SendAuth.Req();
                        req.scope = "snsapi_userinfo";
                        req.state = "wechat_sdk_demo_test";
                        wxApi.sendReq(req);
                    }
                }
            });
        }else{
            rl_hezuo.setVisibility(View.INVISIBLE);
        }

        //微信联合登录广播接收
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                final String data = intent.getStringExtra("data");

                try {
                    if("cancel".equals(data)){
                        if(dialogLoading != null)
                            dialogLoading.dismiss();
                        if(dialog != null)
                            dialog.dismissAllowingStateLoss();
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    JSONObject json = new JSONObject(data);
                    if(json.has("uuid")){
                        UiUtils.showToast("请绑定您的手机号");
                        uuid = json.optString("uuid");
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                startActivityForResult(new Intent(UserRegistrationActivity.this, BindMobileActivity.class).putExtra("uuid", uuid), 0);
                                overridePendingTransition(R.anim.slide_in_right, R.anim.activity_anim_stay);
                            }
                        });

                    }else{
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                done(data);
                            }
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    if(dialogLoading != null)
                        dialogLoading.dismiss();
                    if(dialog != null)
                        dialog.dismissAllowingStateLoss();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.ymx.data");
        registerReceiver(receiver, filter);
    }
    private float height;
    /**初始化广告图*/
    public void initBanner(){
        Object obj = SharedPreferencesHelper.getObject(SharePreferenceKeys.LOGIN_BANNER);
        mIvLoginBanner.setVisibility(View.GONE);
//        v_margin.setVisibility(View.VISIBLE);
        if(null!=obj&&obj instanceof LoginBanner){
            loginBanner = (LoginBanner) obj;
            if(!StringUtils.isEmpty(loginBanner.image)){
                mIvLoginBanner.setVisibility(View.VISIBLE);
//                v_margin.setVisibility(View.GONE);
                if (height == 0){
                    height = loginBanner.imgRatio == 0 ? DensityUtils.dp2px(this, 130) :
                        DeviceUtils.getScreenWidth(this) / loginBanner.imgRatio;
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT, (int) height);
                    mIvLoginBanner.setLayoutParams(params);
                }
                Picasso.with(this).load(DataManager.getInstance().getImageUrl(loginBanner.image, DeviceUtils.getScreenWidth(this))).into(mIvLoginBanner);
            }
        }
    }
    public static void animtionToLogin(BaseNaviFragmentGroupActivity context, int type) {
        if(context==null){
            return;
        }
        Intent mIntent = new Intent(context, UserRegistrationActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("fromType", type);
        mIntent.putExtras(bundle);
        context.startActivity(mIntent);
    }

    @OnClick({
        R.id.iv_login_banner
    })
    /**点击广告图跳转*/
    public void onIvLoginBannerClicked(View view){
        if (null!=loginBanner&&!TextUtils.isEmpty(loginBanner.url)) {
            Intent intent = new Intent(UserRegistrationActivity.this, WebViewActivity.class);
//            intent.putExtra(WebViewActivity.EXTRA_TITLE, getString(R.string.login_agree_title));
            intent.putExtra(WebViewActivity.EXTRA_URL, loginBanner.url);
            startActivity(intent);
        }
    }
    @OnClick({
            R.id.get_verify_code_button
    })
    public void onGetVerifyCodeButtonClicked(View view) {
        MobclickAgent.onEvent(this, StatConstants.LOGIN_GET_SMS_CODE);
        mGetVerifyCodeButton.setEnabled(false);
        mYmxDataService.getVerifyCode(getPhoneNumber())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            startCountDown();
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            UiUtils.toastError(
                                SystemFramework.getInstance().getGlobalContext(), throwable);
                            mGetVerifyCodeButton.setEnabled(true);
                        }
                    });
        mVerifyCodeEditText.requestFocus();
    }

    @OnClick({
            R.id.submit_verify_code_button
    })
    public void onSubmitVerifyCodeButtonClicked(View view) {
        if (!checkedInputData()){
            return;
        }
        MobclickAgent.onEvent(this, StatConstants.LOGIN_SEND_SMS_CODE);
        setCommitBackground(false);

        mYmxDataService.checkUser(getPhoneNumber(), getVerifyCode())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<Pair<String, User>>() {
                        @Override
                        public void call(Pair<String, User> pair) {
                            User user = pair.second;
                            user.token = pair.first;
                            SharedPreferencesHelper.saveUser(user,
                                SharePreferenceKeys.CURRENT_USER);
                            mDataManager.put(CacheKeys.TOKEN, pair.first);
                            mDataManager.put(CacheKeys.CURRENT_USER, pair.second);
                            mSharedPreferences.edit()
                                .putString(CacheKeys.TOKEN, pair.first)
                                .apply();
                            setCommitBackground(true);
                            setResult(RESULT_OK);
                            //初始化小红点
                            SharedPreferencesHelper.commitBoolean(Constants.ISUPDATEORDERTABRPOINT, true);
                            if (mPlusMinusIconMessage != null
                                && mPlusMinusIconMessage.icon != null) {
                                mPlusMinusIconMessage.message = mPlusMinusIconMessage.icon.mCurrentButtonState
                                    + "/IsFisrt";
                                EventBus.getDefault().postSticky(mPlusMinusIconMessage);
                                mPlusMinusIconMessage = null;
                            } else {
                                EventBus.getDefault()
                                    .postSticky(
                                        new String(
                                            Constants.EVENT_BUS_LOGIN_SUCCESS_MESSAGE));
                                EventBus.getDefault()
                                    .postSticky(new String(Constants.EVENT_BUS_GET_CART));
                            }
                            if(CartManager.getInstance().mCartGoodsItems!=null&&CartManager.getInstance().mCartGoodsItems.size()>0)syncUnLoginCartData();
                            jump();
                            finish();
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            UiUtils.toastError(
                                SystemFramework.getInstance().getGlobalContext(), throwable);
                            setCommitBackground(true);
                        }
                    });
    }
    public boolean checkedInputData(){
        boolean isChecked=false;
        boolean phoneNumberMatched = getPhoneNumber().matches(PHONE_NUMBER_REGEX);
        if (!phoneNumberMatched){
            UiUtils.showToast("请输入正确的手机号");
            return isChecked;
        }
        if (TextUtils.isEmpty(getVerifyCode())){
            UiUtils.showToast("请输入验证码");
            return isChecked;
        }
        if (getVerifyCode().length()<6){
            UiUtils.showToast("验证码长度不足6位");
            return isChecked;
        }
        boolean codeMatched=getVerifyCode().matches(VERIFY_CODE_REGEX);
        if (codeMatched){
            isChecked=true;
        }
        return isChecked;
    }

    public void jump() {
        AppConfig mAppConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (mAppConfig == null)
            return;
        switch (fromType) {
            case MyFragment.EDITPERSON:
//                UserInfoEditActivity.startActivity(this);
                break;
            case MyFragment.BALANCE:
                MobclickAgent.onEvent(this, StatConstants.MY_ACCOUNT_BAlANCE_CLICK);
                Intent intentAccount = new Intent(this, WebViewActivity.class);
                intentAccount.putExtra(WebViewActivity.EXTRA_TITLE, "账户余额");
                intentAccount.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.rechargeUrl);
                startActivity(intentAccount);
                break;
            case MyFragment.COUPON:
                MobclickAgent.onEvent(this, StatConstants.MY_FRUIT_COUPON_CLICK);
                Intent intentCoupon = new Intent(this, WebViewActivity.class);
                intentCoupon.putExtra(WebViewActivity.EXTRA_TITLE,
                        getString(R.string.personal_mine_bonus));
                intentCoupon.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.bonusUrl);
                startActivity(intentCoupon);
                break;
            case MyFragment.POINT:
                Intent intentMall = new Intent(this, WebViewActivity.class);
                intentMall.putExtra(WebViewActivity.EXTRA_TITLE, "我的积分");
                intentMall.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.creditMallUrl);
                startActivity(intentMall);
                break;
            case MyFragment.INVITE:
                Intent intentInvite = new Intent(this, WebViewActivity.class);
                intentInvite.putExtra(WebViewActivity.EXTRA_TITLE,
                        getString(R.string.invite_friend));
                intentInvite.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.invitationUrl);
                startActivity(intentInvite);
                break;
            case MyFragment.ADDRESS:
                MobclickAgent.onEvent(this, StatConstants.MY_ADDRESS_MANAGER_CLICK);
                Intent intent = new Intent(this, ShowAddressesActivity.class).putExtra(
                        ShowAddressesActivity.EXTRA_MODE,
                        ShowAddressesActivity.MANAGE_ADDRESS_MODE);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void startCountDown() {
        mCountDownTimer = new CountDownTimer(120 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mGetVerifyCodeButton.setText((millisUntilFinished / 1000) + "秒后重试");
            }

            @Override
            public void onFinish() {
                mGetVerifyCodeButton.setEnabled(true);
                mGetVerifyCodeButton.setText("获取验证码");
                mCountDownTimer = null;
            }
        };
        mCountDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
        EventBus.getDefault().unregister(this);
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    private String getVerifyCode() {
        return mVerifyCodeEditText.getText() != null ? mVerifyCodeEditText.getText().toString()
                : "";
    }

    private String getPhoneNumber() {
        return mPhoneNumberEditText.getText() != null ? mPhoneNumberEditText.getText().toString()
                : "";
    }

    private void onVerifyCodeChanged() {
        setCommitBackground(getVerifyCode().matches(VERIFY_CODE_REGEX));
    }

    private void onPhoneNumberChanged() {
        boolean phoneNumberMatched = getPhoneNumber().matches(PHONE_NUMBER_REGEX);
        mGetVerifyCodeButton.setEnabled(mCountDownTimer == null && phoneNumberMatched);
        setCommitBackground(getVerifyCode().matches(VERIFY_CODE_REGEX)
            && phoneNumberMatched);
    }

    @Override
    protected String getTitleBarText() {
        return getString(R.string.login_ymx);
    }

    public void onEventMainThread(PlusMinusIconMessage message) {
        if (message != null && message.message.contains("/Login")) {
            mPlusMinusIconMessage = message;
            EventBus.getDefault().removeStickyEvent(message);
        }
    }
    public void setCommitBackground(boolean isClickable){
        if (isClickable) {
            mSubmitVerifyCodeButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.orange_button_normal_bg));
        }
        else {
            mSubmitVerifyCodeButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_button_disabled));
        }
    }
    private void syncUnLoginCartData(){
        if(null==mCartUpdateAPI)mCartUpdateAPI = new CartUpdateAPI(new SyncUnLoginCallback());
        mCartUpdateAPI.syncUnLoginCartData();
    }
    CartUpdateAPI mCartUpdateAPI;

    class SyncUnLoginCallback implements Callback{

        @Override
        public void success(Object o, Response response) {
            String json = "";
            JSONObject jsonObject = null;
            try {
                json = Strings.inputStream2String(response.getBody().in());
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

            if (!TextUtils.isEmpty(json)) {
                try {
                    jsonObject = new JSONObject(json);

                } catch (JSONException e) {
                    e.printStackTrace();
                    return;
                }
            }

            // 返回error信息
            if (jsonObject != null) {
                JSONObject errorObject = jsonObject.optJSONObject("error");
                if (errorObject != null) {// 返回错误信息
                    com.yimixian.app.rest.response.Error error = new com.yimixian.app.rest.response.Error();
                    error.code = errorObject.optInt("code");
                    error.message = errorObject.optString("message");
                    if (!TextUtils.isEmpty(error.message)) {
                        UiUtils.showToast(error.message);
                        return;
                    }
                }
            }
            CartUpdate cartUpdate = mCartUpdateAPI.parseJson(jsonObject);
            CartManager.getInstance().clearOfflineData();
            CartManager.getInstance().updateCartGoods(cartUpdate);
            EventBus.getDefault().postSticky(new String(Constants.SYNC_UNLOGIN_DATA_SUCCESS));
        }

        @Override
        public void failure(RetrofitError error) {
            UiUtils.showToast(SystemFramework.getInstance().getGlobalContext()
                .getString(R.string.network_error));
        }
    }

    private void done(String result){
        try {
            if(dialogLoading != null)
                dialogLoading.dismiss();
            if(dialog != null)
                dialog.dismissAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            JSONObject json = new JSONObject(result);
            if(json.has("error")){
                UiUtils.showToast(json.optJSONObject("error").optString("message"));
                if(mVerifyCodeEditText.getText().length() == 6)
                    setCommitBackground(true);
                return;
            }
            User user = new User();
            user.token = json.optString("token");
            json = json.getJSONObject("user");
            user.age = json.optInt("age");
            user.career = json.optString("career");
            user.head_img = json.optString("head_img");
            user.name = json.optString("name");
            user.nickName = json.optString("nickName");
            user.registeringTimestamp = json.optString("registering_timestamp");
            user.remainingBalance = (float) json.optDouble("remaining_balance");
            user.remainingCredit = json.optInt("remaining_credit");
            user.sex = json.optInt("sex");
            user.tel = json.optString("tel");
            user.unfinishedOrderCount = json.optInt("unfinished_order_count");
            user.careerMap = new ArrayList<KV>();
            JSONArray array = json.getJSONArray("career_map");
            for (int i = 0; i < array.length(); i++) {
                JSONObject each = array.optJSONObject(i);
                KV kv = new KV();
                kv.key = each.optString("key");
                kv.value = each.optString("value");
                user.careerMap.add(kv);
            }
            user.level = new UserLevel();
            user.level.level = json.optInt("level");
            user.level.accumulativeCredit = json.optInt("accumulative_credit");
            user.level.shortfallCredit = json.optInt("shortfall_credit");
            user.sexMap = new ArrayList<KV>();
            array = json.getJSONArray("sex_map");
            for (int i = 0; i < array.length(); i++) {
                JSONObject each = array.optJSONObject(i);
                KV kv = new KV();
                kv.key = each.optString("key");
                kv.value = each.optString("value");
                user.sexMap.add(kv);
            }
            SharedPreferencesHelper.saveUser(user,
                    SharePreferenceKeys.CURRENT_USER);
            mDataManager.put(CacheKeys.TOKEN, user.token);
            mDataManager.put(CacheKeys.CURRENT_USER, user);
            mSharedPreferences.edit()
                    .putString(CacheKeys.TOKEN, user.token)
                    .apply();
            if(mVerifyCodeEditText.getText().length() == 6)
                setCommitBackground(true);
            else
                setCommitBackground(false);
            setResult(RESULT_OK);
            //初始化小红点
            SharedPreferencesHelper.commitBoolean(Constants.ISUPDATEORDERTABRPOINT, true);
            if (mPlusMinusIconMessage != null
                    && mPlusMinusIconMessage.icon != null) {
                mPlusMinusIconMessage.message = mPlusMinusIconMessage.icon.mCurrentButtonState
                        + "/IsFisrt";
                EventBus.getDefault().postSticky(mPlusMinusIconMessage);
                mPlusMinusIconMessage = null;
            } else {
                EventBus.getDefault()
                        .postSticky(
                                new String(
                                        Constants.EVENT_BUS_LOGIN_SUCCESS_MESSAGE));
                EventBus.getDefault()
                        .postSticky(new String(Constants.EVENT_BUS_GET_CART));
            }
            if(CartManager.getInstance().mCartGoodsItems!=null&&CartManager.getInstance().mCartGoodsItems.size()>0)syncUnLoginCartData();
            jump();
            finish();
            overridePendingTransition(0, 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //目前只有绑定手机号页面一个返回
        if(intent != null){
            String data = intent.getStringExtra("data");
            if(!Strings.isNullOrEmpty(data)){
                done(data);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(dialogLoading != null){
            dialogLoading.dismiss();
        }
    }
}
